import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Query,
  Param,
  UseGuards,
  Request,
  ParseIntPipe,
  UploadedFile,
  UseInterceptors,
  BadRequestException,
  ParseFilePipe,
  MaxFileSizeValidator,
  FileTypeValidator,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { ProfileService } from './profile.service';
import { diskStorage } from 'multer';
import { extname } from 'path';
import {
  UpdateProfileDto,
  ChangePasswordDto,
  UpdateReadingPreferencesDto,
  GetActivityTimelineDto,
} from './dto/profile.dto';

@Controller('user/profile')
export class ProfileController {
  constructor(private readonly profileService: ProfileService) {}

  /**
   * 获取用户基本信息
   */
  @UseGuards(JwtAuthGuard)
  @Get()
  async getUserProfile(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.getUserProfile(userId);
  }

  /**
   * 更新用户基本信息
   */
  @UseGuards(JwtAuthGuard)
  @Put()
  async updateProfile(
    @Request() req,
    @Body() updateProfileDto: UpdateProfileDto,
  ) {
    const userId = req.user.userId;
    return this.profileService.updateProfile(userId, updateProfileDto);
  }

  /**
   * 修改密码
   */
  @UseGuards(JwtAuthGuard)
  @Put('password')
  async changePassword(
    @Request() req,
    @Body() changePasswordDto: ChangePasswordDto,
  ) {
    const userId = req.user.userId;
    return this.profileService.changePassword(
      userId,
      changePasswordDto.oldPassword,
      changePasswordDto.newPassword,
    );
  }

  /**
   * 上传头像
   */
  @UseGuards(JwtAuthGuard)
  @Post('avatar')
  @UseInterceptors(
    FileInterceptor('avatar', {
      storage: diskStorage({
        destination: './uploads/avatars',
        filename: (req, file, cb) => {
          const randomName = Array(32)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('');
          cb(null, `${randomName}${extname(file.originalname)}`);
        },
      }),
      fileFilter: (req, file, cb) => {
        const allowedTypes = [
          'image/jpeg',
          'image/png',
          'image/gif',
          'image/webp',
        ];
        if (!allowedTypes.includes(file.mimetype)) {
          cb(
            new BadRequestException('只支持jpg、png、gif、webp格式的图片'),
            false,
          );
        } else {
          cb(null, true);
        }
      },
      limits: {
        fileSize: 2 * 1024 * 1024, // 2MB
      },
    }),
  )
  async uploadAvatar(
    @Request() req,
    @UploadedFile(
      new ParseFilePipe({
        validators: [
          new MaxFileSizeValidator({ maxSize: 2 * 1024 * 1024 }), // 2MB
          new FileTypeValidator({
            fileType: /(jpg|jpeg|png|gif|webp)$/,
          }),
        ],
      }),
    )
    file: Express.Multer.File,
  ) {
    const userId = req.user.userId;
    const avatarUrl = `/uploads/avatars/${file.filename}`;
    return this.profileService.updateAvatar(userId, avatarUrl);
  }

  /**
   * 获取用户统计数据
   */
  @UseGuards(JwtAuthGuard)
  @Get('stats')
  async getUserStats(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.getUserStats(userId);
  }

  /**
   * 获取用户阅读统计
   */
  @UseGuards(JwtAuthGuard)
  @Get('reading-stats')
  async getReadingStats(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.getReadingStats(userId);
  }

  /**
   * 获取用户活动时间线
   */
  @UseGuards(JwtAuthGuard)
  @Get('activity-timeline')
  async getUserActivityTimeline(
    @Request() req,
    @Query() getActivityTimelineDto: GetActivityTimelineDto,
  ) {
    const userId = req.user.userId;
    return this.profileService.getUserActivityTimeline(
      userId,
      getActivityTimelineDto.limit,
    );
  }

  /**
   * 获取用户推荐的小说
   */
  @UseGuards(JwtAuthGuard)
  @Get('recommendations')
  async getRecommendedNovels(
    @Request() req,
    @Query() query: { limit?: number },
  ) {
    const userId = req.user.userId;
    const limit = query.limit ? parseInt(query.limit.toString()) : 10;
    return this.profileService.getRecommendedNovels(userId, limit);
  }

  /**
   * 获取用户阅读偏好分析
   */
  @UseGuards(JwtAuthGuard)
  @Get('reading-preferences')
  async getReadingPreferences(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.getReadingPreferences(userId);
  }

  /**
   * 更新阅读偏好设置
   */
  @UseGuards(JwtAuthGuard)
  @Put('reading-preferences')
  async updateReadingPreferences(
    @Request() req,
    @Body() updateReadingPreferencesDto: UpdateReadingPreferencesDto,
  ) {
    const userId = req.user.userId;
    return this.profileService.updateReadingPreferences(
      userId,
      updateReadingPreferencesDto,
    );
  }

  /**
   * 获取用户评论列表
   */
  @UseGuards(JwtAuthGuard)
  @Get('comments')
  async getUserComments(
    @Request() req,
    @Query() query: { page?: number; limit?: number },
  ) {
    const userId = req.user.userId;
    const page = query.page ? parseInt(query.page.toString()) : 1;
    const limit = query.limit ? parseInt(query.limit.toString()) : 10;
    return this.profileService.getUserComments(userId, { page, limit });
  }

  /**
   * 获取用户最近阅读
   */
  @UseGuards(JwtAuthGuard)
  @Get('recent-reading')
  async getRecentReading(@Request() req, @Query() query: { limit?: number }) {
    const userId = req.user.userId;
    const limit = query.limit ? parseInt(query.limit.toString()) : 10;
    return this.profileService.getRecentReading(userId, limit);
  }

  /**
   * 获取用户收藏分类统计
   */
  @UseGuards(JwtAuthGuard)
  @Get('favorite-categories')
  async getFavoriteCategories(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.getFavoriteCategories(userId);
  }

  /**
   * 获取用户阅读时长统计
   */
  @UseGuards(JwtAuthGuard)
  @Get('reading-time-stats')
  async getReadingTimeStats(
    @Request() req,
    @Query() query: { period?: string },
  ) {
    const userId = req.user.userId;
    const period = query.period || 'month'; // week, month, year
    return this.profileService.getReadingTimeStats(userId, period);
  }

  /**
   * 清空用户活动记录
   */
  @UseGuards(JwtAuthGuard)
  @Delete('activities')
  async clearActivities(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.clearUserActivities(userId);
  }

  /**
   * 导出用户数据
   */
  @UseGuards(JwtAuthGuard)
  @Get('export')
  async exportUserData(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.exportUserData(userId);
  }

  /**
   * 注销账号
   */
  @UseGuards(JwtAuthGuard)
  @Delete('account')
  async deleteAccount(@Request() req, @Body() body: { password: string }) {
    const userId = req.user.userId;
    return this.profileService.deleteAccount(userId, body.password);
  }

  /**
   * 获取用户隐私设置
   */
  @UseGuards(JwtAuthGuard)
  @Get('privacy')
  async getPrivacySettings(@Request() req) {
    const userId = req.user.userId;
    return this.profileService.getPrivacySettings(userId);
  }

  /**
   * 更新隐私设置
   */
  @UseGuards(JwtAuthGuard)
  @Put('privacy')
  async updatePrivacySettings(
    @Request() req,
    @Body()
    privacySettings: {
      profilePublic: boolean;
      readingHistoryPublic: boolean;
      favoritesPublic: boolean;
      commentsPublic: boolean;
    },
  ) {
    const userId = req.user.userId;
    return this.profileService.updatePrivacySettings(userId, privacySettings);
  }
}
